//
//  PlayMusicViewController.m
//  MusicPlayer
//
//  Created by dlios on 15-5-26.
//  Copyright (c) 2015年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "PlayMusicViewController.h"
#import "Singleton.h"
#import <StreamingKit/STKAudioPlayer.h>
#import "RecommendLatestModel.h"
#import <AVFoundation/AVFoundation.h>
#import <AFNetworking/AFNetworking.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "state.h"
#import "NovelModel.h"
#import "NovelDataBase.h"

@interface PlayMusicViewController ()
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) UIButton *pauseButton;
@property (nonatomic, retain) UIButton *nextButton;
@property (nonatomic, retain) UIButton *lastButton;
@property (nonatomic, retain) UILabel *songNameLabel;
@property (nonatomic, retain) UILabel *singerLabel;
@property (nonatomic, retain) UIImageView *albumImageView;
@property (nonatomic, retain) CABasicAnimation *rotationAnimation;
@property (nonatomic, retain) UIButton *playOrder;
@property (nonatomic, retain) UIProgressView *progress;
@property (nonatomic, retain) NSTimer *time;
@property (nonatomic, retain) UISlider *slider;
@property (nonatomic, retain) UILabel *currentTime;
@property (nonatomic, retain) UILabel *songTime;
@property (nonatomic, retain) NSMutableArray *array;
@property (nonatomic, retain) NSMutableArray *lrcArray;
@property (nonatomic, copy) NSString *lrcStr;
@property (nonatomic, retain) UILabel *lrcLabel;
@property (nonatomic, retain) NSMutableArray *timeArray;
@property (nonatomic, retain) NSMutableDictionary *LRCDictionary;

//@property (nonatomic, retain) Singleton *singleton;
@end

@implementation PlayMusicViewController
- (void)dealloc
{
    [_songUrl release];
    [_playButton release];
    [_pauseButton release];
    [_nextButton release];
    [_lastButton release];
    [_songArray release];
    [_songName release];
    [_songNameLabel release];
    [_singer release];
    [_songListArray release];
    [_singerLabel release];
    [_albumImageView release];
    [_rotationAnimation release];
    [_playOrder release];
    [_progress release];
    [_time release];
    [_slider release];
    [_songTime release];
    [_currentTime release];
    [_array release];
    [_lrcArray release];
    [_lrcStr release];
    [_lrcLabel release];
    [super dealloc];
}
- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.songArray = [NSMutableArray array];
        self.songListArray = [NSMutableArray array];
        self.lrcArray = [NSMutableArray array];
        self.timeArray = [NSMutableArray array];
        self.LRCDictionary = [NSMutableDictionary dictionary];
        
        
//        UIImageView *back = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
//        [back setImage:[UIImage imageNamed:@"gray.jpg"]];
//        [self.view addSubview:back];
        
    }
    return self;
}

- (void)loadView
{
    [super loadView];
}

- (void)viewDidLoad {
    // 创建后退图片
    UIBarButtonItem *exits = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back.png"] style:UIBarButtonItemStyleDone target:self action:@selector(exitsAction:)];
    self.navigationItem.leftBarButtonItem = exits;


    UIButton *collect = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width/375*310, self.view.frame.size.height / 667 * 440, 30, 30)];

    [collect setImage:[UIImage imageNamed:@"love.png"] forState:UIControlStateNormal];
    [collect addTarget:self action:@selector(collecAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:collect];
    [collect release];
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    

    
    [self createView];
    [self connect];
    
}

#pragma mark - 使用AFNetworking网络连接
- (void)connect
{
    RecommendLatestModel *model = [self.songListArray objectAtIndex:self.num];
//    self.songNameLabel.text = model.song_name;
    
    // 解析tableHeaderView的网络数据
    AFHTTPSessionManager*m = [AFHTTPSessionManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *str1 = @"http://api.raventech.cn/api/music/search?album_name=&appkey=54679361&appversion=ios1.3.0&cate_type=0&client_time=2015-05-21%2015%3A28%3A39";
    NSString *str2 = [NSString stringWithFormat:@"&content=%@", model.song_name];
    NSString *str3 = [str2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *str4 = @"&deviceid=86D47CC5-7337-4186-98C3-6EB77C5C8CD3&deviceusername=%25E5%25A4%25AA%%25E9%2598%25B3&key=";
    NSString *str5 = model.song_name;
    NSString *str6 = [str5 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *str7 = @"&network_type=1&page=1&searchtype=0&zone=Asia%%252FShanghai%2520%2528GMT%252B8%2529";
    // 把歌名拼接成字符串
    NSString *str = [NSString stringWithFormat:@"%@%@%@%@%@", str1, str3, str4, str6, str7];
    NSString *strrr = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    [m GET:strrr parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        // 点击进入到播放界面后，移除底部播放状态条
        NSArray *arr = self.view.window.subviews;
        UIView *view = [arr objectAtIndex:1];
        view.alpha = 0;
        
        UIButton *button = [view.subviews objectAtIndex:0];
        [button setImage:[UIImage imageNamed:@"pause.ico"] forState:UIControlStateNormal];
        button.alpha = 0;
        
        UIButton *button1 = [view.subviews objectAtIndex:1];
        button1.alpha = 0;
        
        UIImageView *imageView = [view.subviews objectAtIndex:2];
        imageView.alpha = 0;
        
        
        UILabel *label = [view.subviews lastObject];
        label.alpha = 0;
        UIImageView *albumImageView = [view.subviews objectAtIndex:3];
        albumImageView.alpha = 0;
        
        NSData *data = [NSData dataWithData:responseObject];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        NSDictionary *dic2 = [dic objectForKey:@"info"];
        NSMutableArray *array = [dic2 objectForKey:@"data"];
        self.array = [NSMutableArray array];
        for (NSMutableDictionary *dic in array) {
            RecommendLatestModel *model = [[RecommendLatestModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.array addObject:model];
        }
        
        if (self.array.count != 0) {
            RecommendLatestModel *model = [self.array objectAtIndex:0];
            NSNumber *str = model.id;
            NSLog(@"%@", str);
            
            AFHTTPSessionManager*m2 = [AFHTTPSessionManager manager];
            m2.responseSerializer = [AFHTTPResponseSerializer serializer];
            NSString *str10 = [NSString stringWithFormat:@"http://api.raventech.cn/api/music/lyric?id=%@", model.id];
            
            [m2 GET:str10 parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                NSData *data = [NSData dataWithData:responseObject];
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
                NSDictionary *dic2 = [dic objectForKey:@"info"];
                self.lrcStr = [dic2 objectForKey:@"lyric"];
                self.lrcLabel.numberOfLines = 0;
                self.lrcLabel.text = self.lrcStr;
                
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                
            }];
        } else {
            self.lrcLabel.text = @"暂无歌词信息";
        }
        
        
        [self.view reloadInputViews];
        // 判断如果
        if (self.array.count > 0) {
            RecommendLatestModel *model = [[RecommendLatestModel alloc] init];
            model = [self.array objectAtIndex:0];
            [_albumImageView sd_setImageWithURL:[NSURL URLWithString:model.pic_url] placeholderImage:nil];
            Singleton *singleton = [Singleton shareManager];
            singleton.songUrl = model.pic_url;
            
            RecommendLatestModel *model1 = [self.songListArray objectAtIndex:self.num];
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:model1.song_name forKey:@"songName"];
            [defaults setObject:model1.singer_name forKey:@"singer"];
            [defaults setObject:model.pic_url forKey:@"pic"];
            [defaults setObject:self.songUrl forKey:@"songUrl"];

            
            
            UILabel *label = [view.subviews lastObject];

            label.text = [NSString stringWithFormat:@"%@ - %@", [defaults objectForKey:@"songName"], [defaults objectForKey:@"singer"]];
            
//            UIButton *button = [view.subviews objectAtIndex:3];
//            [button setImage:[UIImage imageNamed:@"enter.jpg"] forState:UIControlStateNormal];
            UIImageView *albumImageView = [view.subviews objectAtIndex:3];

            [albumImageView sd_setImageWithURL:[NSURL URLWithString:model.pic_url] placeholderImage:nil];

        } else {
            RecommendLatestModel *model1 = [self.songListArray objectAtIndex:self.num];
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:model1.song_name forKey:@"songName"];
            [defaults setObject:model1.singer_name forKey:@"singer"];
            [defaults setObject:model.pic_url forKey:@"pic"];
            [defaults setObject:self.songUrl forKey:@"songUrl"];
            
            NSArray *arr = self.view.window.subviews;
            UIView *view = [arr objectAtIndex:1];
            UILabel *label = [view.subviews lastObject];
            label.text = [NSString stringWithFormat:@"%@ - %@", [defaults objectForKey:@"songName"], [defaults objectForKey:@"singer"]];
            UIImageView *imageView = [view.subviews objectAtIndex:3];
            [imageView setImage:[UIImage imageNamed:@"enter.jpg"]];
             [_albumImageView setImage:[UIImage imageNamed:@"enter.jpg"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
    }];
}

- (void)createView
{
    NSArray *arr = self.view.window.subviews;
    UIView *view = [arr objectAtIndex:1];
    view.alpha = 0;
    
    UIButton *button = [view.subviews objectAtIndex:0];
    [button setImage:[UIImage imageNamed:@"pause.ico"] forState:UIControlStateNormal];
    button.alpha = 0;
    
    UIButton *button1 = [view.subviews objectAtIndex:1];
    button1.alpha = 0;
    
    UIImageView *imageView = [view.subviews objectAtIndex:2];
    imageView.alpha = 0;
    
    
    UILabel *label = [view.subviews lastObject];
    label.alpha = 0;
    UIImageView *albumImageView = [view.subviews objectAtIndex:3];
    albumImageView.alpha = 0;
    
    // 创建唱片和歌词scrollView
    UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - self.view.frame.size.width / 2 / 2, self.view.frame.size.height / 667 * 150, self.view.frame.size.width / 2 , self.view.frame.size.width / 2)];
    scroll.contentSize = CGSizeMake(scroll.frame.size.width * 2, 0);
    scroll.pagingEnabled = YES;
    [self.view addSubview:scroll];
    [scroll release];
    
    // 创建旋转的唱片视图
    self.albumImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,scroll.frame.size.width, scroll.frame.size.height)];
    _albumImageView.clipsToBounds = YES;
    _albumImageView.layer.cornerRadius = self.view.frame.size.width / 2 / 2;
    _albumImageView.userInteractionEnabled = YES;
    [scroll addSubview:_albumImageView];
    [_albumImageView release];
    
    // 创建旋转动画
    self.rotationAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    _rotationAnimation.toValue = [NSNumber numberWithFloat:M_PI * 2.0];
    _rotationAnimation.duration = 10;
    _rotationAnimation.repeatCount = INFINITY;
    [_albumImageView.layer addAnimation:_rotationAnimation forKey:@"rotation"];
    
    UIScrollView *lrcScroll = [[UIScrollView alloc] initWithFrame:CGRectMake(scroll.frame.size.width, 0, scroll.frame.size.width, scroll.frame.size.height)];
    lrcScroll.contentSize = CGSizeMake(0, lrcScroll.frame.size.width * 5);
    [scroll addSubview:lrcScroll];
    [lrcScroll release];
    
    // 创建歌词label
    
    self.lrcLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, lrcScroll.frame.size.width, lrcScroll.frame.size.height * 5)];
    
    [lrcScroll addSubview:_lrcLabel];
    [_lrcLabel release];
    
    
    
    // 创建暂停按钮
    self.pauseButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 25, self.view.frame.size.width / 6 * 6.8, self.view.frame.size.width / 6, self.view.frame.size.width / 6)];
    [self.pauseButton setBackgroundImage:[UIImage imageNamed:@"pause.ico"] forState:UIControlStateNormal];
    [self.pauseButton addTarget:self action:@selector(pauseAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.pauseButton];
    [_pauseButton release];
    // 创建下一首按钮
    self.nextButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 * 3.8, self.view.frame.size.width / 6 * 7, self.view.frame.size.width / 9, self.view.frame.size.width / 9)];
    [self.nextButton setBackgroundImage:[UIImage imageNamed:@"next.ico"] forState:UIControlStateNormal];
    [self.nextButton addTarget:self action:@selector(nextAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_nextButton];
    
    // 创建上一首按钮
    self.lastButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 * 1.6, self.view.frame.size.width / 6 * 7, self.view.frame.size.width / 9, self.view.frame.size.width / 9)];
    [_lastButton setBackgroundImage:[UIImage imageNamed:@"last.ico"] forState:UIControlStateNormal];
    [self.lastButton addTarget:self action:@selector(lastAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_lastButton];
    
//    // 创建停止按钮
//    UIButton *stopButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 * 4.8, self.view.frame.size.width / 6 * 6.8, self.view.frame.size.width / 6, self.view.frame.size.width / 6)];
//    [stopButton setBackgroundImage:[UIImage imageNamed:@"stop.ico"] forState:UIControlStateNormal];
//    [stopButton addTarget:self action:@selector(stopAction:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:stopButton];
//    [stopButton release];
    
    // 创建歌名Label
    self.songNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.width / 6 * 0.4, self.view.frame.size.width, self.view.frame.size.width / 6)];
    self.songNameLabel.textAlignment = NSTextAlignmentCenter;
    [_songNameLabel setFont:[UIFont systemFontOfSize:23]];
    self.songNameLabel.text = self.songName;
    [self.view addSubview:_songNameLabel];
    [_songNameLabel release];
    
    // 创建歌手Label
    self.singerLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, self.view.frame.size.width / 6 * 0.9, self.view.frame.size.width, self.view.frame.size.width / 6)];
    self.singerLabel.textAlignment = NSTextAlignmentCenter;
    [_singerLabel setFont:[UIFont systemFontOfSize:17]];
    self.singerLabel.text = [NSString stringWithFormat:@"— %@ —", self.singer];
    [self.view addSubview:_singerLabel];
    [_singerLabel release];
    
    // 创建播放顺序按钮
    self.playOrder = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 8, self.view.frame.size.width / 6 * 7, self.view.frame.size.width / 9, self.view.frame.size.width / 9)];
    [self.playOrder setBackgroundImage:[UIImage imageNamed:@"xunhuan.ico"] forState:UIControlStateNormal];
    [self.playOrder addTarget:self action:@selector(playOrderAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:self.playOrder];
    [self.playOrder release];
    
    // 计时器
    self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
    
    // 创建slider
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 , self.view.frame.size.width / 6 * 6.3, self.view.frame.size.width / 6 * 4, self.view.frame.size.width / 6 * 0.5)];
    [self.slider addTarget:self action:@selector(sliderAction) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.slider];
    [self.slider release];
    
    // 创建当前播放时间
    self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake(0 , self.view.frame.size.width / 6 * 6.3, self.view.frame.size.width / 6, self.view.frame.size.width / 6 * 0.5)];
    self.currentTime.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.currentTime];
    [self.currentTime release];
    
    // 创建歌曲总时间
    self.songTime = [[UILabel alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 6 * 5.1, self.view.frame.size.width / 6 * 6.3, self.view.frame.size.width / 6, self.view.frame.size.width / 6 *0.5)];
    self.songTime.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:self.songTime];
    [self.songTime release];
    
    // 从上一个界面点击进来后根据状态判断自动开始播放
    Singleton *singleton = [Singleton shareManager];
    singleton.array = self.songArray;
    singleton.songListArray = self.songListArray;
    singleton.num = self.num;
    
    if ([self.songUrl isEqualToString:singleton.url]) {

    } else {
        [singleton playWithUrl:self.songUrl];
        singleton.url = self.songUrl;
        singleton.name = @"播放";
    }
    
    

}

#pragma mark - 返回按钮事件
- (void)exitsAction:(id)sender
{
    [self.navigationController popViewControllerAnimated:YES];
    NSArray *arr = self.view.window.subviews;
    UIView *view = [arr objectAtIndex:1];
    view.alpha = 1;
    
    UIButton *button = [view.subviews objectAtIndex:0];
    button.alpha = 0.9;
    
    UIButton *button1 = [view.subviews objectAtIndex:1];
    button1.alpha = 0.9;
    
    UIImageView *imageView = [view.subviews objectAtIndex:2];
    imageView.alpha = 0.9;
    
    
    UILabel *label = [view.subviews lastObject];
    label.alpha = 0.9;
    UIImageView *albumImageView = [view.subviews objectAtIndex:3];
    albumImageView.alpha = 0.9;

}



- (void)collecAction:(id)sender
{
//    
//    state *single = [state shareManager];
//    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
//    single.login = [de objectForKey:@"state"];
//    if ([single.login isEqualToString:@"yes"]) {
//        
//        NovelModel *model = [[NovelModel alloc] init];
//        
//        model.songName = self.songName;
//        model.singerName = self.singer;
//        model.songId = self.songUrl;
//        
//        [NovelDataBase insertWithModel:model];
//
//    } else {
//        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录后再收藏" delegate:nil cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
//        [alert show];
//        [alert release];
//        
//        
//    }
    
    NovelModel *model = [[NovelModel alloc] init];
    
    model.song_name = self.songName;
    model.singer_name = self.singer;
    model.songId = self.songUrl;
    
    [NovelDataBase insertWithModel:model];
    


    
    
}

#pragma mark - 播放顺序的事件

- (void)playOrderAction
{
    Singleton *singleton = [Singleton shareManager];
    if ([singleton.order isEqualToString:@"单曲"]) {
        [self.playOrder setBackgroundImage:[UIImage imageNamed:@"xunhuan.ico"] forState:UIControlStateNormal];
        singleton.order = @"顺序";
    } else if ([singleton.order isEqualToString:@"随机"]) {
        [self.playOrder setBackgroundImage:[UIImage imageNamed:@"danqu.ico"] forState:UIControlStateNormal];
        singleton.order = @"单曲";
    } else if ([singleton.order isEqualToString:@"顺序"] || singleton.order == nil){
        [self.playOrder setBackgroundImage:[UIImage imageNamed:@"suiji.ico"] forState:UIControlStateNormal];
        singleton.order = @"随机";
    }
}

#pragma mark - slider的事件
- (void)sliderAction
{
    Singleton *singer = [Singleton shareManager];
//    NSLog(@"%.2f", self.slider.value);
    [singer.audio seekToTime:self.slider.value * singer.audio.duration];
}

#pragma mark- progress的事件
- (void)progressAction
{
    Singleton *singer = [Singleton shareManager];

    NSInteger currentTimeSec = singer.audio.progress / 60;
    NSInteger currentTimeMin = (NSInteger)singer.audio.progress % 60;
    
    NSInteger songTimeSec = singer.audio.duration / 60;
    NSInteger songTimeMin = (NSInteger)singer.audio.duration % 60;
    
    self.currentTime.text = [NSString stringWithFormat:@"%ld:%ld", currentTimeSec, currentTimeMin];
    self.songTime.text = [NSString stringWithFormat:@"%ld:%ld", songTimeSec, songTimeMin];
    self.slider.value = singer.audio.progress / singer.audio.duration;
    if (singer.audio.progress > 0) {
        if (singer.audio.progress > (singer.audio.duration - 1)) {
            [_time invalidate];
            self.slider.value = 0;
            self.time = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(progressAction) userInfo:nil repeats:YES];
            [self nextAction:nil];
            
        }
    }
    
}



#pragma mark - 暂停按钮的事件
- (void)pauseAction:(id)sender
{
    NSArray *arr = self.view.window.subviews;
    UIView *view = [arr objectAtIndex:1];
    UIButton *button = [view.subviews objectAtIndex:0];
    
    Singleton *singleton = [Singleton shareManager];
    NSString *str = @"播放";
    // 判断，如果单例属性等于“播放”，就暂停音乐，并停止动画；否则就继续播放，添加动画
    if ([str isEqualToString:singleton.name]) {
        singleton.name = @"暂停";
        [singleton.audio pause];
        [self.pauseButton setBackgroundImage:[UIImage imageNamed:@"play.ico"] forState:UIControlStateNormal];
        [self.albumImageView.layer removeAllAnimations];
        
        [button setImage:[UIImage imageNamed:@"play.ico"] forState:UIControlStateNormal];
        
    }
    else
    {
        singleton.name = @"播放";
        [singleton.audio resume];
        [self.pauseButton setBackgroundImage:[UIImage imageNamed:@"pause.ico"] forState:UIControlStateNormal];
        [_albumImageView.layer addAnimation:_rotationAnimation forKey:@"rotation"];
        [button setImage:[UIImage imageNamed:@"pause.ico"] forState:UIControlStateNormal];
    }
    
}

#pragma mark - 停止按钮的事件
//- (void)stopAction:(id)sender
//{
//    [self.audio stop];
//    [self.view addSubview:self.playButton];
//}

#pragma mark - 下一首按钮的事件
- (void)nextAction:(id)sender
{
    Singleton *singleton = [Singleton shareManager];
    
    // 如果是顺序播放走判断
    if ([singleton.order isEqualToString:@"顺序"] || singleton.order == nil) {
        self.num++;
        singleton.num = self.num;
        singleton.name = @"停止";
        
        // 如果到了最后一首歌，在点击下一首的话把self.num归0
        if (self.num == self.songArray.count) {
            self.num = 0;
        }
        
        RecommendLatestModel *model = [self.songListArray objectAtIndex:self.num];
        self.songNameLabel.text = model.song_name;
        self.singerLabel.text = [NSString stringWithFormat:@"— %@ —", model.singer_name];
        
        // 单例播放下一首歌曲
        [singleton playWithUrl:[self.songArray objectAtIndex:self.num]];
        singleton.name = @"播放";
        
        [self.albumImageView setImage:nil];
        [self connect];
        
        
        [self.view reloadInputViews];
    }
    
    // 如果是单曲循环
    if ([singleton.order isEqualToString:@"单曲"]) {
        RecommendLatestModel *model = [self.songListArray objectAtIndex:self.num];
        self.songNameLabel.text = model.song_name;
        self.singerLabel.text = [NSString stringWithFormat:@"— %@ —", model.singer_name];
        // 单例播放下一首歌曲
        [singleton playWithUrl:[self.songArray objectAtIndex:self.num]];
        singleton.name = @"播放";
        
        [self.albumImageView setImage:nil];
        [self connect];
        [self.view reloadInputViews];
    }
    
    // 如果是随机播放
    if ([singleton.order isEqualToString:@"随机"]) {
        NSInteger num = arc4random() % (self.songListArray.count);
        RecommendLatestModel *model = [self.songListArray objectAtIndex:num];
        singleton.num = num;
        self.songNameLabel.text = model.song_name;
        self.singerLabel.text = [NSString stringWithFormat:@"— %@ —", model.singer_name];
        
        // 单例播放下一首歌曲
        [singleton playWithUrl:[self.songArray objectAtIndex:num]];
        singleton.name = @"播放";
        
        [self.albumImageView setImage:nil];
        self.num = num;
        [self.view reloadInputViews];
        [self connect];
    }
    
    
    
    // 点击下一首先移除动画再重新添加
    [self.albumImageView.layer removeAllAnimations];
    [_albumImageView.layer addAnimation:_rotationAnimation forKey:@"rotation"];
    
}

#pragma mark - 上一首按钮的事件
- (void)lastAction:(id)sender
{
    self.num--;
//    [self.audio stop];
    Singleton *singleton = [Singleton shareManager];
    singleton.name = @"停止";
    
    if (self.num == -1) {
        self.num = (int)self.songArray.count - 1;
    }
    
    // 从model中取值
    RecommendLatestModel *model = [self.songListArray objectAtIndex:self.num];
    self.songNameLabel.text = model.song_name;
    self.singerLabel.text = [NSString stringWithFormat:@"— %@ —", model.singer_name];
    
    [self.albumImageView setImage:nil];
    
    // 播放上一首的歌曲
    [singleton playWithUrl:[self.songArray objectAtIndex:self.num]];
    singleton.name = @"播放";
    
    [self.albumImageView.layer removeAllAnimations];
    [_albumImageView.layer addAnimation:_rotationAnimation forKey:@"rotation"];
    
    [self connect];
}

#pragma mark - 获取歌词
- (void)initLRC {
    NSArray *array = [self.lrcStr componentsSeparatedByString:@"\n"];
    for (int i = 0; i < [array count]; i++) {
        NSString *linStr = [array objectAtIndex:i];
        NSArray *lineArray = [linStr componentsSeparatedByString:@"]"];
        if ([lineArray[0] length] > 8) {
            NSString *str1 = [linStr substringWithRange:NSMakeRange(3, 1)];
            NSString *str2 = [linStr substringWithRange:NSMakeRange(6, 1)];
            if ([str1 isEqualToString:@":"] && [str2 isEqualToString:@"."]) {
                NSString *lrcStr = [lineArray objectAtIndex:1];
                NSString *timeStr = [[lineArray objectAtIndex:0] substringWithRange:NSMakeRange(1, 5)];//分割区间求歌词时间
                //把时间 和 歌词 加入词典
                [_LRCDictionary setObject:lrcStr forKey:timeStr];
                [_timeArray addObject:timeStr];//timeArray的count就是行数
            }
        }
    }
}


@end
